package com.miaomiao.filter;

import cn.hutool.json.JSONUtil;
import com.miaomiao.common.Result;
import com.miaomiao.utils.WebUtils;
import io.jsonwebtoken.lang.Strings;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class VerifyLoginCodeFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if("POST".equals(request.getMethod()) && "/user/login".equals(request.getServletPath())){
            String code = request.getParameter("code");
            String verifyCode = (String) request.getSession().getAttribute("login-code");
            if(!StringUtils.hasText(code) || StringUtils.hasText(verifyCode) || !verifyCode.toLowerCase().equals(code.toLowerCase())){
                WebUtils.renderString(response, JSONUtil.toJsonStr(Result.error("验证码错误")));
            }else{
                filterChain.doFilter(request,response);
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }
}
